﻿using AsscerMVCN2512.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web.Mvc;

namespace AsscerMVCN2512.Controllers
{
    public class DamageRepairController : Controller
    {
        private AssetDBEntities1 db = new AssetDBEntities1();

        // 报损维修管理页面
        public ActionResult Index()
        {
            // 获取当前登录用户信息
            var currentUser = GetCurrentUser();

            // 添加调试信息
            if (currentUser != null)
            {
                System.Diagnostics.Debug.WriteLine($"DamageRepair Index - 当前用户: {currentUser.EmpolyName}, RoleID: {currentUser.RoleID}, IsAdmin: {currentUser.RoleID == 1}");
            }
            else
            {
                System.Diagnostics.Debug.WriteLine("DamageRepair Index - 当前用户未登录或获取失败");
                // 如果用户未登录，重定向到登录页
                return RedirectToAction("LoginProject", "EmpolyInfo");
            }

            bool isAdmin = currentUser?.RoleID == 1; // RoleID=1是管理员
            ViewBag.IsAdmin = isAdmin;
            ViewBag.CurrentUserID = currentUser?.EmpolyID ?? 0;

            // 将 isAdmin 转换为字符串传递给前端
            ViewBag.IsAdminStr = isAdmin.ToString().ToLower();

            return View();
        }

        // 获取报损维修记录列表
        [HttpPost]
        public JsonResult GetDamageRepairList(int page = 1, int limit = 10, string assetName = "", string empolyName = "", int? recordState = null)
        {
            try
            {
                var currentUser = GetCurrentUser();
                if (currentUser == null)
                {
                    return Json(new { code = 1, msg = "用户未登录" });
                }

                bool isAdmin = currentUser.RoleID == 1;

                // 基础查询
                var query = from damage in db.DamageRecordInfo
                            join detail in db.AssetDetailInfo on damage.AssetDetailID equals detail.AssetDetailID
                            join asset in db.AssetInfo on detail.AssetID equals asset.AssetID
                            join empoly in db.EmpolyInfo on damage.EmpolyID equals empoly.EmpolyID
                            select new
                            {
                                damage,
                                detail,
                                asset,
                                empoly
                            };

                // 严格的权限控制
                if (!isAdmin)
                {
                    // 普通员工只能查看自己的记录
                    query = query.Where(x => x.damage.EmpolyID == currentUser.EmpolyID);

                    // 调试日志
                    System.Diagnostics.Debug.WriteLine($"普通用户 {currentUser.EmpolyName} 查看自己的报修记录，用户ID: {currentUser.EmpolyID}");
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine($"管理员 {currentUser.EmpolyName} 查看所有报修记录");
                }

                // 搜索条件
                if (!string.IsNullOrEmpty(assetName))
                {
                    query = query.Where(x => x.asset.AssetName.Contains(assetName));
                }

                if (!string.IsNullOrEmpty(empolyName) && isAdmin) // 只有管理员可以按申请人搜索
                {
                    query = query.Where(x => x.empoly.EmpolyName.Contains(empolyName));
                }

                if (recordState.HasValue)
                {
                    query = query.Where(x => x.damage.RecordState == recordState.Value);
                }

                // 获取总数
                int totalCount = query.Count();

                // 分页数据
                var list = query
                    .OrderByDescending(x => x.damage.DamageDate)
                    .Skip((page - 1) * limit)
                    .Take(limit)
                    .Select(x => new
                    {
                        DamageRecordID = x.damage.DamageRecordID,
                        AssetName = x.asset.AssetName,
                        AssetDetailNum = x.detail.AssetDetailNum,
                        EmpolyName = x.empoly.EmpolyName,
                        DamageDate = x.damage.DamageDate,
                        DamageCauses = x.damage.DamageCauses,
                        ProblemDescription = x.damage.ProblemDescription,
                        RecordState = x.damage.RecordState,
                        Repairman = x.damage.Repairman ?? "待处理",
                        RepairDates = x.damage.RepairDates,
                        DamageRecordReMark = x.damage.DamageRecordReMark ?? "暂无",
                        CurrentUserIsAdmin = isAdmin // 添加当前用户权限信息
                    })
                    .ToList();

                return Json(new
                {
                    code = 0,
                    msg = "success",
                    count = totalCount,
                    data = list
                });
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"获取报修记录列表异常: {ex.Message}");
                return Json(new { code = 1, msg = "查询失败：" + ex.Message });
            }
        }

        // 获取当前用户正在使用的资产（用于报修）
        [HttpPost]
        public JsonResult GetCurrentUserAssets()
        {
            try
            {
                var currentUser = GetCurrentUser();
                if (currentUser == null)
                {
                    return Json(new { code = 1, msg = "用户未登录" });
                }

                var assets = from record in db.AssetDetailRecordInfo
                             join detail in db.AssetDetailInfo on record.AssetDetailID equals detail.AssetDetailID
                             join asset in db.AssetInfo on detail.AssetID equals asset.AssetID
                             where record.EmpolyID == currentUser.EmpolyID &&
                                   record.AssetDetailRecordReturnDate == null && // 未归还
                                   detail.AssetDetailServiceState == 0 && // 正常状态
                                   detail.AssetDetailDumState == 0 // 未报废
                             select new
                             {
                                 AssetDetailID = detail.AssetDetailID,
                                 AssetDetailNum = detail.AssetDetailNum,
                                 AssetName = asset.AssetName,
                                 AssetModel = asset.AssetModel
                             };

                var list = assets.ToList();

                System.Diagnostics.Debug.WriteLine($"用户 {currentUser.EmpolyName} 获取可用资产数量: {list.Count}");

                return Json(new { code = 0, data = list });
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"获取用户资产异常: {ex.Message}");
                return Json(new { code = 1, msg = ex.Message });
            }
        }

        // 申请报修
        [HttpPost]
        public JsonResult ApplyRepair(int assetDetailID, DateTime damageDate, string damageCauses, string problemDescription, string problemImage, string remark)
        {
            try
            {
                var currentUser = GetCurrentUser();
                if (currentUser == null)
                {
                    return Json(new { code = 1, msg = "用户未登录" });
                }

                // 验证参数
                if (string.IsNullOrEmpty(damageCauses))
                {
                    return Json(new { code = 1, msg = "损坏原因不能为空" });
                }

                if (string.IsNullOrEmpty(problemDescription))
                {
                    return Json(new { code = 1, msg = "问题描述不能为空" });
                }

                // 检查资产是否存在且属于当前用户
                var assetDetail = db.AssetDetailInfo.Find(assetDetailID);
                if (assetDetail == null)
                {
                    return Json(new { code = 1, msg = "资产不存在" });
                }

                // 检查资产是否属于当前用户且正在使用
                var usingRecord = db.AssetDetailRecordInfo
                    .FirstOrDefault(r => r.AssetDetailID == assetDetailID &&
                                        r.EmpolyID == currentUser.EmpolyID &&
                                        r.AssetDetailRecordReturnDate == null);

                if (usingRecord == null)
                {
                    return Json(new { code = 1, msg = "只能报修自己正在使用的资产" });
                }

                using (var transaction = db.Database.BeginTransaction())
                {
                    try
                    {
                        // 创建报修记录
                        var damageRecord = new DamageRecordInfo
                        {
                            AssetDetailID = assetDetailID,
                            EmpolyID = currentUser.EmpolyID,
                            DamageDate = damageDate,
                            DamageCauses = damageCauses,
                            ProblemDescription = problemDescription,
                            ProblemImage = problemImage,
                            RecordState = 0, // 申报中
                            DamageRecordReMark = remark
                        };

                        db.DamageRecordInfo.Add(damageRecord);

                        // 更新资产状态为需要维修
                        assetDetail.AssetDetailServiceState = 1;

                        db.SaveChanges();
                        transaction.Commit();

                        System.Diagnostics.Debug.WriteLine($"用户 {currentUser.EmpolyName} 成功申请报修，资产ID: {assetDetailID}");

                        return Json(new { code = 0, msg = "报修申请提交成功" });
                    }
                    catch (Exception ex)
                    {
                        transaction.Rollback();
                        System.Diagnostics.Debug.WriteLine($"报修申请失败: {ex.Message}");
                        return Json(new { code = 1, msg = "报修申请失败：" + ex.Message });
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"报修申请异常: {ex.Message}");
                return Json(new { code = 1, msg = "报修申请失败：" + ex.Message });
            }
        }

        // 获取报修详情
        [HttpPost]
        public JsonResult GetDamageDetail(int damageRecordID)
        {
            try
            {
                var currentUser = GetCurrentUser();
                if (currentUser == null)
                {
                    return Json(new { code = 1, msg = "用户未登录" });
                }

                var detail = (from damage in db.DamageRecordInfo
                              join assetDetail in db.AssetDetailInfo on damage.AssetDetailID equals assetDetail.AssetDetailID
                              join asset in db.AssetInfo on assetDetail.AssetID equals asset.AssetID
                              join empoly in db.EmpolyInfo on damage.EmpolyID equals empoly.EmpolyID
                              where damage.DamageRecordID == damageRecordID
                              select new
                              {
                                  DamageRecordID = damage.DamageRecordID,
                                  AssetName = asset.AssetName,
                                  AssetDetailNum = assetDetail.AssetDetailNum,
                                  EmpolyName = empoly.EmpolyName,
                                  EmpolyID = damage.EmpolyID, // 添加申请人ID用于权限检查
                                  DamageDate = damage.DamageDate,
                                  DamageCauses = damage.DamageCauses,
                                  ProblemDescription = damage.ProblemDescription,
                                  ProblemImage = damage.ProblemImage,
                                  RecordState = damage.RecordState,
                                  Repairman = damage.Repairman,
                                  RepairDates = damage.RepairDates,
                                  DamageRecordReMark = damage.DamageRecordReMark
                              }).FirstOrDefault();

                if (detail == null)
                {
                    return Json(new { code = 1, msg = "记录不存在" });
                }

                // 权限检查：普通员工只能查看自己的记录
                bool isAdmin = currentUser.RoleID == 1;
                if (!isAdmin && detail.EmpolyID != currentUser.EmpolyID)
                {
                    return Json(new { code = 1, msg = "没有权限查看此记录" });
                }

                return Json(new { code = 0, data = detail });
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"获取报修详情异常: {ex.Message}");
                return Json(new { code = 1, msg = ex.Message });
            }
        }

        // 处理维修（管理员）
        [HttpPost]
        public JsonResult ProcessRepair(int damageRecordID, string repairman, DateTime repairDate, string remark)
        {
            try
            {
                var currentUser = GetCurrentUser();
                if (currentUser?.RoleID != 1)
                {
                    System.Diagnostics.Debug.WriteLine($"用户 {currentUser?.EmpolyName} 尝试执行管理员操作被拒绝");
                    return Json(new { code = 1, msg = "没有权限执行此操作" });
                }

                var damageRecord = db.DamageRecordInfo.Find(damageRecordID);
                if (damageRecord == null)
                {
                    return Json(new { code = 1, msg = "记录不存在" });
                }

                if (damageRecord.RecordState == 1)
                {
                    return Json(new { code = 1, msg = "该记录已处理" });
                }

                using (var transaction = db.Database.BeginTransaction())
                {
                    try
                    {
                        // 更新维修记录
                        damageRecord.RecordState = 1; // 已处理
                        damageRecord.Repairman = repairman;
                        damageRecord.RepairDates = repairDate;
                        if (!string.IsNullOrEmpty(remark))
                        {
                            damageRecord.DamageRecordReMark = remark;
                        }

                        // 更新资产状态为正常
                        var assetDetail = db.AssetDetailInfo.Find(damageRecord.AssetDetailID);
                        if (assetDetail != null)
                        {
                            assetDetail.AssetDetailServiceState = 0; // 恢复正常
                        }

                        db.SaveChanges();
                        transaction.Commit();

                        System.Diagnostics.Debug.WriteLine($"管理员 {currentUser.EmpolyName} 处理了维修记录 ID: {damageRecordID}");

                        return Json(new { code = 0, msg = "维修处理完成" });
                    }
                    catch (Exception ex)
                    {
                        transaction.Rollback();
                        System.Diagnostics.Debug.WriteLine($"处理维修失败: {ex.Message}");
                        return Json(new { code = 1, msg = "处理失败：" + ex.Message });
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"处理维修异常: {ex.Message}");
                return Json(new { code = 1, msg = "处理失败：" + ex.Message });
            }
        }

        // 修复后的 GetCurrentUser 方法
        private EmpolyInfo GetCurrentUser()
        {
            try
            {
                // 从 Session 获取
                if (Session["user"] != null)
                {
                    var sessionUser = Session["user"] as EmpolyInfo;
                    if (sessionUser != null)
                    {
                        // 从数据库重新获取确保数据最新
                        var dbUser = db.EmpolyInfo.Find(sessionUser.EmpolyID);
                        if (dbUser != null)
                        {
                            return dbUser;
                        }
                    }
                }

                System.Diagnostics.Debug.WriteLine("GetCurrentUser: 未找到当前用户信息");
                return null;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"GetCurrentUser 异常: {ex.Message}");
                return null;
            }
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}